import { BadRequestException, ForbiddenException, Injectable, Logger } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { DataSource, Like, Repository } from "typeorm";
import { MediaEntity } from "src/entity";
import { MediaAddDto, MediaQueryDto, MediaRemoveDto, MediaUpdateDto } from "src/dto/media";
import { UserService } from "./user.service";
import { ConfigService } from "@nestjs/config";
import { pagination } from "src/common/pagination.query";

@Injectable()
export class MediaService {
    private readonly logger = new Logger(MediaService.name);

    constructor(
        private readonly dataSource: DataSource,
        @InjectRepository(MediaEntity) private readonly mediaRepository: Repository<MediaEntity>,
        private readonly userService: UserService,
        private readonly configService: ConfigService,
    ) {}

    query(id: number, dto: MediaQueryDto) {
        const qb = this.mediaRepository.createQueryBuilder("media").where("media.user = :id", { id });
        if (dto.where?.filepath) {
            qb.andWhere("media.filepath LIKE :filepath", {
                filepath: `%${dto.where.filepath}%`,
            });
        }
        return pagination(qb, dto);
    }

    async add(id: number, dto: MediaAddDto) {
        const user = await this.userService.find(id);
        if (!user) {
            throw new ForbiddenException("用户不存在!");
        }
        this.logger.log(`requset add user: ${user.username}`);

        const result = await this.mediaRepository
            .createQueryBuilder()
            .insert()
            .into(MediaEntity)
            .values({
                ...dto,
                user,
            })
            .orUpdate(["title", "duration", "lastPosition"], ["filepath"])
            .execute();
        return {
            ...dto,
            ...result.generatedMaps[0],
        };
    }

    async update(id: number, dto: MediaUpdateDto) {
        this.logger.log(`requset update user id: ${id} media id: ${dto.id}`);

        const result = await this.mediaRepository.update(
            {
                id: dto.id,
                user: {
                    id,
                },
            },
            dto,
        );
        if (result.affected == 0) throw new BadRequestException("更新失败");
    }

    async remove(id: number, dto: MediaRemoveDto) {
        this.logger.log(`requset remove user id: ${id} media id: ${dto.id}`);

        const result = await this.mediaRepository.delete({
            id: dto.id,
            user: {
                id,
            },
        });

        if (result.affected == 0) throw new BadRequestException("删除失败");
    }
}
